#!/bin/bash
# 30 */4 * * * PATH=/usr/local/bin:/usr/bin:/bin /data/cron_scripts/backup_rds_and_redis.sh >> /data/cron_scripts/backup_rds_and_redis.log
# AWS配置
AWS_REGION="eu-central-1"

# RDS配置
RDS_INSTANCE_ID="meetcha-mysql"

# ElastiCache配置
ELASTICACHE_CLUSTER_ID="doli-redis-001"

# 计算两天前当前时间加10分钟的时间戳
TARGET_TIME=$(date -d '2 days ago +10 minutes' +%Y-%m-%dT%H:%M:%S)

# 删除指定时间之前的手动创建的RDS快照
echo "---RDS---删除两天前加10分钟前的手动创建的RDS快照..."
OLD_RDS_SNAPSHOT_IDS=$(aws rds describe-db-snapshots --db-instance-identifier $RDS_INSTANCE_ID --region $AWS_REGION --query "DBSnapshots[?SnapshotType=='manual'&&SnapshotCreateTime<'$TARGET_TIME'].DBSnapshotIdentifier" --output text)
if [ -n "$OLD_RDS_SNAPSHOT_IDS" ]; then
  RDS_SNAPSHOT_ARRAY=($OLD_RDS_SNAPSHOT_IDS)
  for SNAPSHOT_ID in "${RDS_SNAPSHOT_ARRAY[@]}"; do
    SNAPSHOT_ID=$(echo "$SNAPSHOT_ID" | tr -cd '[:print:]')  # 移除控制字符
    aws rds delete-db-snapshot --db-snapshot-identifier "$SNAPSHOT_ID" --region $AWS_REGION --profile default
    echo "---RDS---已删除RDS快照：$SNAPSHOT_ID"
  done
else
  echo "---RDS---未找到需要删除的RDS快照"
fi

# 删除指定时间之前的手动创建的ElastiCache快照
echo "---ElastiCache---删除两天前加10分钟前的手动创建的ElastiCache快照..."
OLD_ELASTICACHE_SNAPSHOT_IDS=$(aws elasticache describe-snapshots --cache-cluster-id $ELASTICACHE_CLUSTER_ID --region $AWS_REGION --query "Snapshots[?SnapshotSource=='manual'&&NodeSnapshots[?SnapshotCreateTime<'$TARGET_TIME']].SnapshotName" --output text)
if [ -n "$OLD_ELASTICACHE_SNAPSHOT_IDS" ]; then
  ELASTICACHE_SNAPSHOT_ARRAY=($OLD_ELASTICACHE_SNAPSHOT_IDS)
  for SNAPSHOT_ID in "${ELASTICACHE_SNAPSHOT_ARRAY[@]}"; do
    SNAPSHOT_ID=$(echo "$SNAPSHOT_ID" | tr -cd '[:print:]')  # 移除控制字符
    aws elasticache delete-snapshot --snapshot-name "$SNAPSHOT_ID" --region $AWS_REGION --profile default
    echo "---ElastiCache---已删除ElastiCache快照：$SNAPSHOT_ID"
  done
else
  echo "---ElastiCache---未找到需要删除的ElastiCache快照"
fi

# 备份RDS
echo "---RDS---开始备份RDS..."
RDS_SNAPSHOT_ID=$(aws rds create-db-snapshot --db-instance-identifier $RDS_INSTANCE_ID --db-snapshot-identifier $RDS_INSTANCE_ID-$(date +%Y%m%d%H%M%S) --region $AWS_REGION --profile default --query "DBSnapshot.DBSnapshotIdentifier" --output text)
echo "---RDS---RDS备份成功：$RDS_SNAPSHOT_ID"

# 备份ElastiCache
echo "---ElastiCache---开始备份ElastiCache..."
ELASTICACHE_SNAPSHOT_ID=$(aws elasticache create-snapshot --cache-cluster-id $ELASTICACHE_CLUSTER_ID --snapshot-name $ELASTICACHE_CLUSTER_ID-$(date +%Y%m%d%H%M%S) --region $AWS_REGION --profile default --query "Snapshot.SnapshotName" --output text)
echo "---ElastiCache---ElastiCache备份成功：$ELASTICACHE_SNAPSHOT_ID"